import { storageName } from '@/config'
import Taro from '@tarojs/taro'

export default {
  namespace: 'app',
  state: {
    // ...Taro.getStorageSync(storageName),
  },
  effects: {
    *AsyncChangeCount(_, { put }) {
      const value = yield new Promise(resolve => {
        setTimeout(() => {
          resolve(2)
        }, 2000)
      })
      yield put({
        type: 'changeCount',
        payload: {
          count: value
        }
      })
    },
    *initStoreData({ payload }, { call, put }) {
      const res = yield call(Taro.getStorage, { key: storageName })
      yield put({ type: 'updateState', payload: res.data })
    },
    *update({ payload }, { call, put, select }) {
      // 不使用reducers,因为rn中不支持Taro.setStorage这个API
      const state: any = yield put({
        type: 'updateState',
        payload 
      })
      yield call(Taro.setStorage, { key: storageName, data: state.payload })
    }
  },
  reducers: {
    updateState(state, { payload }) {
      state = {
        ...state,
        ...payload
      }
      return { ...state }
    }
  },
  subscriptions: {
    // 初始化state。因为rn中不支持Taro.getStorageSync这个API
    setup({ dispatch }) {
      dispatch({ type: 'initStoreData' })
    }
  }
}
